package net.stevechaloner.idea.ffs.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.project.Project;
import net.stevechaloner.idea.ffs.QueryFactory;
import net.stevechaloner.idea.ffs.model.xml.SearchPlugin;
import org.jetbrains.annotations.NotNull;

/**
 * @author Steve Chaloner
 */
class FirefoxSearchPluginAction extends AbstractSearchAction
{
    /**
     * The search provider.
     */
    private final SearchPlugin searchPlugin;

    /**
     * Initialises a new instance of this class based on a {@link SearchPlugin}.
     *
     * @param project the project
     * @param searchPlugin the search provider
     */
    FirefoxSearchPluginAction(@NotNull Project project,
                              @NotNull SearchPlugin searchPlugin)
    {
        super(project);

        this.searchPlugin = searchPlugin;
        setName(searchPlugin.getShortName().getValue());
    }

    // javadoc inherited
    public void actionPerformed(AnActionEvent e)
    {
        Editor editor = (Editor)e.getDataContext().getData("editor");
        if (editor != null)
        {
            String encoding = searchPlugin.getInputEncoding().getValue();
            String term = getInputFromEditor(editor,
                                             encoding == null ? "UTF-8" : encoding);
            if (!StringUtil.isEmptyOrSpaces(term))
            {
                String query = QueryFactory.buildQuery(term,
                                                       searchPlugin);
                openUrl(query);
            }
            else
            {
                showInvalidInput(editor.getComponent());
            }
        }
    }
}
